<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\library\RedisService;

/**
 * 公交线路
 *
 * @icon fa fa-circle-o
 */
class Lines extends Backend
{

    /**
     * Lines模型对象
     * @var \app\admin\model\Lines
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Lines;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function timetable()
    {
        $id=input('ids',0);
        $lines=$this->model::get($id);
        if(!$lines) return $this->error('请选择线路');
        $this->assign("lines",$lines);
        $redis=new RedisService();
        if(!$this->request->isPost()){
            $list=$redis->getHash("line_time_tables",$id);
            $trans=$redis->get("en_ch_list");
            $transList=json_decode($trans,true);
            $new=array_column($transList,null,'en');
            foreach ($list as &$value){
                if(isset($new[$value['station']])){
                    $value['station_en']=$new[$value['station']]['zh'];
                }elseif(!isset($value['station_en'])){
                    $value['station_en']="";
                }
                if(!isset($value['direction'])) $value['direction']=1;
                $value['departure_time']=date("H:i",strtotime($value['times'])+60);
                $value['arrival_time']=$value['times'];
            }
            $this->assign("listJson",json_encode($list,256));
        }else{
            $timeTable=$this->request->post('timetable');
            $list=json_decode($timeTable,true);
            foreach ($list as &$value){
                $value['times']=$value['arrival_time'];
                $tt=$redis->getHash("station_line_time_tables_".$value['station'],$id);
                if(!$tt){
                    $tt=array();
                }
                if(!isset($value['direction'])) $value['direction']=1;
                $tt[$value['times']]=$value;
                $redis->setHash("station_line_time_tables_".$value['station'],$id,$tt);
            }
            $redis->setHash("line_time_tables",$id,$list);
            $this->success('ok');
        }
        return $this->view->fetch();
    }
}
